/*****************************************************************************************
  Project   : The Impact of Unions on Non-union Wage Setting: Threats and Bargaining
  Authors   : David A. Green, Ben M. Sand, Iain G. Snoddy, Jeanne Tschopp
  Date      : August 2025
  Output    : Data for Figure 3
  Notes     : This script should be run after main data cleaning and variable construction
*****************************************************************************************/

* Begin script
clear all
set more off

* Your code starts here

global Use_data "${wd}/decomp_out_${ind}_${area}_All_case_0.dta"

// -----> transitions
use ${wd}/ipums_ind_trans/transitions_All_case_6.dta, clear

* non-union to union
keep if union == 0 & union_2 ==1

bysort year2 detind: keep if _n==1

keep year2 $ind phi_tt

tempfile trans
save `trans', replace

// -----> union premium	


use  $Use_data, clear

	egen id = group(year2 $area $ind)
	tsset id union
	gen uprem2 = D.prem
	

// ----- > weights for city aggregation

	replace reg_wgt = 0 if reg_wgt == .
	egen temp = sum(reg_wgt) if year == 1 , by($area $ind  )
	egen wt = mean(temp), by($area $ind ) 
	drop temp

		
// ------> threat

	merge m:1 ${ind} ${area} year2 using  ${wd}/keyvars/union_elections_${area}_${ind}.dta
	tab _merge
	drop _merge
	gen threat  = win_frac_ic_5 
	
// ------> Union_Project_Shared

egen union_share = wtmean(union), by(year2 ${area}) weight(n_jc)


// -------> bring back transitions

sort year2
merge m:1 year2 $ind using `trans'

// ------> Annual level

collapse (mean) threat uprem union_share phi_tt [aw = wt], by(year2)


// Rel to base year
	foreach var of varlist  threat uprem union_share phi_tt  {
		egen tmp      = mean(`var') if year == 1, by(year)
		egen `var'_0  = mean(tmp), 
		replace `var' = (`var' - `var'_0) / `var'_0 * 100
		drop tmp *0
		}
	
save ${wd}/Trends_figure_dta.dta, replace	

/*
// figure 
lab var union_share "Proportion Union"
lab var threat "Threat"
lab var phi_tt  "Transitions"
lab var uprem "Union premium: {it:w} {superscript:U} - {it:w} {superscript:N}"
	
	*drop if year == 5 
	// Figure
	scatter union_share threat phi_tt uprem  year , c(l l l l l) s(d o Oh s) ///
	ytitle("Normalized Percentage Change") ///
	xtitle("Year") ///
	xlabel(1 "1980" 2 "1990" 3 "2000" 4 "2010" 5 "2020", grid) ///
	ylabel(,grid) color(%50 %50 %50 %50 %50 %50) 
*/
